var config = require('../config.json')
var $ = require('./util')
var request = require('request')
var md5 = require('./md5')
var color = require('colors')

// 自动登录中间件

function getPassword () {
  for (var i = 0; i < config.users.length; i++) {
    if (config.users[i].name === config.user_name) {
      return config.users[i].password
    }
  }
}

module.exports = function (req, res, next) {
  if (config.auto_login && !$.cookie && config.remote_data) {
    var name = config.user_name
    console.log('AUTO LOGIN: '.yellow + name)
    var password = getPassword()
    var url = `${config.remote_host}/service/${config.app}/signin?name=${name}&password=${md5(name, password)}`
    console.log(url.gray)
    var opts = {
      method: 'get',
      url
    }
    request(opts, (error, response, body) => {
      if (response && response.caseless && response.caseless.dict['set-cookie']) {
        $.cookie = response.caseless.dict['set-cookie'][0]
        console.log('AUTO LOGIN DONE!'.yellow)
      } else {
        console.log('AUTO LOGIN ERROR'.red)
        error && console.log(error)
        body && console.log(body)
      }
      next()
    })
  } else {
    next()
  }
}
